package com.captjack.sort;

import java.util.Arrays;

/**
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2022/10/11 12:26
 * package com.captjack.docker.simple.application
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] nums = {11, 24, 5, 32, 50, 34, 54, 76};
        System.out.println("归并排序前:" + Arrays.toString(nums));
        int[] temp = new int[8];
        mergeSort(nums, 0, nums.length - 1, temp);
        System.out.println("归并排序后:" + Arrays.toString(nums));
    }

    private static void mergeSort(int[] nums, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }
        int mid = left + right >> 1;
        // 拆分
        mergeSort(nums, left, mid, temp);
        mergeSort(nums, mid + 1, right, temp);
        // 合并
        merge(nums, left, mid, right, temp);
    }

    private static void merge(int[] nums, int left, int mid, int right, int[] temp) {
        int i = left, j = mid + 1;
        int tempIndex = 0;
        // 这里保证把长度短的数组合并完成
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[tempIndex++] = nums[i++];
            } else {
                temp[tempIndex++] = nums[j++];
            }
        }
        // 合并未处理的部分
        while (i <= mid) {
            temp[tempIndex++] = nums[i++];
        }
        while (j <= right) {
            temp[tempIndex++] = nums[j++];
        }
        // 回写排序结果
        for (int k = 0; k < right - left + 1; k++) {
            nums[k + left] = temp[k];
        }
    }

}
